import Vue from 'vue'
import VueRouter from 'vue-router'

import Home from '@/components/home'

// import Layout from '@/views/layout'

import Project from '@/views/backend/project'
import Doc from '@/views/backend/doc'
import Workbench from '@/views/backend/workbench'

const Layout = (resolve) => {
  return require.ensure([], () => {
    resolve(require('@/views/layout'))
  })
}
// import Login from '@/components/login'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/management',
    name: 'management',
    component: Layout,
    children: [
      {
        path: '/project',
        name: 'Project',
        component: Project,
        meta: {
          login: true
        }
      },
      {
        path: '/doc',
        name: 'Doc',
        component: Doc,
        meta: {
          login: false
        }
      },
      {
        path: '/workbench',
        name: 'Workbench',
        component: Workbench,
        meta: {
          login: true
        }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../components/login.vue')
  },
  {
    path: '*',
    redirect: '/'
  }
]

const router = new VueRouter({
  mode: 'history',
  linkActiveClass: 'is-active',
  routes
})

router.beforeEach((to, from, next) => {
  // 判断该页面是否需要登录  login标识为true就是需要登录才能有权限进入
  if (to.matched.some(item => item.meta.login)) {
    // router.app 指向根实例 这里的this不能用因为是箭头函数
    const info = router.app.$local.fetch('I CAN')

    info.login
      ? next()
      : router.push({
        path: '/login',
        query: {
          redirect: to.path.slice(1)
        }
      })
  } else {
    next()
  }
})

export default router
